package com.fishery.processing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fishery.processing.entity.MaterialInventory;
import com.fishery.processing.entity.vo.MaterialInventoryVo;
import com.fishery.processing.mapper.MaterialInventoryMapper;
import com.fishery.processing.mapper.ProductMapper;
import com.fishery.processing.service.MaterialInventoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fishery.processing.util.ConvertUtil;
import com.fishery.processing.util.WrapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author run
 * @since 2021-03-12
 */
@Service
public class MaterialInventoryServiceImpl extends ServiceImpl<MaterialInventoryMapper, MaterialInventory> implements MaterialInventoryService {

    @Autowired
    private ConvertUtil convertUtil;

    @Autowired
    private MaterialInventoryMapper materialMapper;

    @Override
    public IPage<MaterialInventoryVo> getMaterialOfFactory(String factoryId, Integer page, Integer size) {
        IPage<MaterialInventory> materialIPage = new Page<>(page ,size);
        QueryWrapper<MaterialInventory> wrapper = new QueryWrapper<>();
        wrapper.inSql("base_id", "SELECT base_id FROM t_processing_factory_info WHERE id = '" + factoryId + "'" );
        return convertUtil.convert(materialMapper.selectPage(materialIPage, wrapper), MaterialInventoryVo.class);
    }

    @Override
    public List<MaterialInventoryVo> getMaterialOfFactory(String factoryId) {
        QueryWrapper<MaterialInventory> wrapper = new QueryWrapper<>();
        wrapper.inSql("base_id", "SELECT base_id FROM t_processing_factory_info WHERE id = '" + factoryId + "'" );
        return convertUtil.convert(materialMapper.selectList(wrapper), MaterialInventoryVo.class);
    }

    @Override
    public boolean createMaterial(MaterialInventory material) {
        Map<String,Object> map = new HashMap<>(1,1);
        map.put("material_id",material.getId());
        List<MaterialInventory> inventories = materialMapper.selectByMap(map);

        if (inventories.isEmpty()){
            return materialMapper.insert(material) > 0;
        }else {
            return materialMapper.update(new MaterialInventory(), WrapperUtil.buildMaterialWrapper(material)) > 0;
        }
    }
}
